package com.admin.business.venueProjectCommercialTenantService;

import com.admin.business.venueProjectCommercialTenantService.entityClasses.VenusProjectCommercialTenantServer;
import com.admin.business.venusProjectCommercialAuditRecord.VenusProjectCommercialAuditRecordDao;
import com.admin.business.venusProjectLifeServiceCost.VenusProjectLifeServiceCostDao;
import com.admin.utils.PayUtil.WXPayUtil;
import com.admin.utils.PayUtility;
import com.admin.utils.PositionUtil;
import com.admin.utils.RandomStrUtil;
import com.admin.utils.RedisUtilKey;
import com.alibaba.druid.util.StringUtils;
import com.tiangong.framework.annotation.OpenApi;
import com.tiangong.framework.bo.CDO;
import com.tiangong.framework.bo.Return;
import lombok.extern.slf4j.Slf4j;
import org.gavaghan.geodesy.Ellipsoid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: 服务表
 * @create: 2022-05-26 18:46:06
 **/
@Service("venueProjectCommercialTenantServiceService")
@Slf4j
public class VenueProjectCommercialTenantServiceService {

    @Resource
    VenueProjectCommercialTenantServiceDao venueProjectCommercialTenantServiceDao;

    @Autowired
    private RedisUtilKey redisTemplate;

    @Resource
    VenusProjectCommercialAuditRecordDao venusProjectCommercialAuditRecordDao;

    //订单dao
    @Resource
    VenusProjectLifeServiceCostDao venusProjectLifeServiceCostDao;
    /**
     * 新增商家服务
     * @param cdoRequest
     * @return
     */
    @OpenApi
    public Return addCommercialService(CDO cdoRequest) {
        //校验是否存在相同名称
        CDO commercialService = venueProjectCommercialTenantServiceDao.getVenueProjectCommercialTenantService(cdoRequest);
        if(commercialService!=null){
            return Return.valueOf(-1, "商户下该服务名称已存在！", false);
        }else{
            venueProjectCommercialTenantServiceDao.venueProjectCommercialTenantServiceAdd(cdoRequest);
        }
        return Return.valueOf(200,"新增服务成功！");
    }


    /**
     * @return 生活服务列表
     * @author whs
     * @create: 2022-05-26
     */
    @OpenApi
    public Return getVenusProjectCommercialTenantServicePage(CDO cdoRequest) {
        //分页参数
        Integer pageIndex = cdoRequest.containsKey("pageIndex") ? cdoRequest.getInteger("pageIndex") : 0;
        int recordSize = cdoRequest.containsKey("recordSize") ? cdoRequest.getInteger("recordSize") : 10;
        cdoRequest.set("recordFrom", pageIndex * recordSize);
        cdoRequest.set("recordSize", recordSize);
        //若距离条件不为空，计算小区到商家距离，近到远排序
        if(cdoRequest.getString("distance") !=null ){
            double projectLongitude = 0;//小区经度
            double projectLatitude = 0;//小区纬度
            double serviceLongitude = 0;//服务经度
            double serviceLatitude = 0;//服务纬度
            //获取小区经纬度,并分割小区经纬度
            String[] splits = venueProjectCommercialTenantServiceDao
                    .selectProjectInfoByProjectId(cdoRequest.getString("project_id")).split(",");
            for (int i = 0;i<splits.length;i++){
                if (i == 0) {
                    projectLongitude = Double.parseDouble(splits[i]);
                }else if (i == 1){
                    projectLatitude = Double.parseDouble(splits[i]);
                }
            }
            //获取服务列表分页数据
            List<VenusProjectCommercialTenantServer> cdoMapperResultList =
                    venueProjectCommercialTenantServiceDao.getVenusProjectCommercialTenantService(cdoRequest);
            //挨个计算小区至商家距离
            for (VenusProjectCommercialTenantServer vs :cdoMapperResultList){
                //获取商家经纬度，并分割赋值
                String[] serviceSplits = vs.getServiceLongitudeAndLatitude().split(",");
                for (int i = 0;i<serviceSplits.length;i++){
                    if (i == 0) {
                        serviceLongitude = Double.parseDouble(splits[i]);
                    }else if (i == 1){
                        serviceLatitude = Double.parseDouble(splits[i]);
                    }
                }
                //调取经纬度计算距离方法
                double distance = PositionUtil.getDistance(projectLongitude, projectLatitude, serviceLongitude, serviceLatitude, Ellipsoid.Sphere);
                vs.setDistance(distance);
            }
            //按距离排序商家
            Collections.sort(cdoMapperResultList,(a, b) ->{
                return (int) (a.getDistance() - b.getDistance());
            });
            boolean isEndPage = false;
            if (cdoMapperResultList.size() < recordSize) {
                isEndPage = true;
            }
            CDO cdoResult = new CDO();
            cdoResult.set("isEndPage", isEndPage);
            cdoResult.set("datalist", cdoMapperResultList);
            int total = venueProjectCommercialTenantServiceDao.getVenusProjectCommercialTenantListTotal(cdoRequest);
            cdoResult.set("total", total);
            return Return.valueOf(cdoRequest);
            //若距离条件为空
        }else {
            List<VenusProjectCommercialTenantServer> cdoMapperResultList = venueProjectCommercialTenantServiceDao.getVenusProjectCommercialTenantService(cdoRequest);
            boolean isEndPage = false;
            if (cdoMapperResultList.size() < recordSize) {
                isEndPage = true;
            }
            CDO cdoResult = new CDO();
            cdoResult.set("isEndPage", isEndPage);
            cdoResult.set("datalist", cdoMapperResultList);
            int total = venueProjectCommercialTenantServiceDao.getVenusProjectCommercialTenantListTotal(cdoRequest);
            cdoResult.set("total", total);
            return Return.valueOf(cdoResult);
        }
    }



    /**
     * @return 生活服务详情
     * @author whs
     * @create: 2022-05-26
     */
    @OpenApi
    public Return getVenusProjectCommercialTenantServiceInfo(CDO cdoRequest) {

        CDO serviceInfo = venueProjectCommercialTenantServiceDao.getVenueProjectCommercialTenantServiceById(cdoRequest);
        CDO cdoResult = new CDO();
        cdoResult.set("serviceInfo", serviceInfo);
        return Return.valueOf(cdoResult);
    }


    /**
     * @return 生活服务下单页面
     * @author whs
     * @create: 2022-05-26
     */
    @OpenApi
    public Return getVenusProjectCommercialTenantServicePayInfo(CDO cdoRequest) {
        CDO serviceInfo = venueProjectCommercialTenantServiceDao.getVenueProjectCommercialTenantServiceInfoById(cdoRequest);
        CDO cdoResult = new CDO();
        cdoResult.set("serviceInfo", serviceInfo);
        return Return.valueOf(cdoResult);
    }


    /**
     * 服务下单页面(推荐服务)
     * 按订单数量排序
     * @param cdoRequest
     * @return
     */
    @OpenApi
    public Return getRecommendService(CDO cdoRequest){
        List<CDO> serviceList = venusProjectCommercialAuditRecordDao.selectRecommendService(cdoRequest);
        CDO cdoResult = new CDO();
        cdoResult.set("serviceList",serviceList);
        return Return.valueOf(200,"该商户推荐服务",cdoResult);
    }
    /**
     * app下单支付
     * @param cdoRequest
     * @return
     */
    @OpenApi
    public Return appServiceOrderPay(CDO cdoRequest){
        if (StringUtils.isEmpty(cdoRequest.getString("tenant_id"))){
            return Return.valueOf(-1,"商家id不可为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_name"))){
            return Return.valueOf(-1,"商家名称不可为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("neighbourhood_id"))){
            return Return.valueOf(-1,"小区id不可为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("neighbourhood_name"))){
            return Return.valueOf(-1,"小区名称不可为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("service_id"))){
            return Return.valueOf(-1,"服务id不可为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("service_name"))){
            return Return.valueOf(-1,"服务名称不可为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("service_earnings"))){
            return Return.valueOf(-1,"服务费用不可为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("visit_time"))){
            return Return.valueOf(-1,"上门时间不可为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("visit_addr"))){
            return Return.valueOf(-1,"上门地址不可为空！");
        }
        //订单表字段
        //存入redis
        CDO redisCdo = new CDO();
        String code = this.rand("UF");//生成订单号
        redisCdo.set("business_id", cdoRequest.getString("tenant_id"));//商户id
        redisCdo.set("commercial_name", cdoRequest.getString("commercial_name"));//商户名称
        redisCdo.set("service_id", cdoRequest.getString("service_id"));//服务id
        redisCdo.set("service_name", cdoRequest.getString("service_name"));//服务名称
        redisCdo.set("pro_id", cdoRequest.getString("neighbourhood_id"));//小区id
        redisCdo.set("pro_name", cdoRequest.getString("neighbourhood_name"));//小区名称
        redisCdo.set("user_id", cdoRequest.getString("user_id"));//支付人id
        redisCdo.set("cost_money", cdoRequest.getString("service_earnings"));//支付金额
        redisCdo.set("user_name", cdoRequest.getString("user_name"));//支付人姓名
        redisCdo.set("user_tel", cdoRequest.getString("user_tel"));//支付人电话
        redisCdo.set("cost_type", 2);//订单类型：1.商户认证 2.服务缴费
        redisCdo.set("cost_state", 0);//订单状态：0.待支付1.已下单2.已接单3.待评价4.待退款5.已完成
        redisCdo.set("pay_type", cdoRequest.getString("pay_type"));//支付方式0.微信1.支付宝
        if (!StringUtils.isEmpty(cdoRequest.getString("cost_remark"))){
            redisCdo.set("cost_remark",cdoRequest.getString("cost_remark"));//订单备注
        }
        redisCdo.set("visit_addr", cdoRequest.getString("visit_addr"));//上门地址
        redisCdo.set("visit_time", cdoRequest.getString("visit_time"));//上门时间


        //唤醒支付
        CDO wakePay = new CDO();
        wakePay.set("id", code);
        wakePay.set("sNotifyUrl", "https://admin.515f.com/tpapi/rest/v1/venueProjectCommercialTenantServiceService/rechargeCallback");
        wakePay.set("attach", "生活服务");
        wakePay.set("body", "生活服务");
        wakePay.set("orderVariable", 1);
        wakePay.set("orderDescription", "微信支付");
        wakePay.set("mweb", "APP");
        cdoRequest.set("service_earnings","0.01");
        wakePay.set("cost_money", cdoRequest.getString("service_earnings"));
        Return paySign = PayUtility.getWXPaySign(wakePay);
        redisTemplate.set(code, redisCdo, 3600L);//存储时长为1个小时，存贮订单id
        return paySign;
    }


    /**
     * 商户app下单回调
     * @param cdoRequest
     * @return
     */
    @OpenApi
    public Return commercialAppOrderCallback(CDO cdoRequest) {
        String strVersion = cdoRequest.getString("data");
        try{
            Map<String, String> mapResult= WXPayUtil.xmlToMap(strVersion);
            //获取订单code
            String trade_state=mapResult.get("return_code");
            if ("SUCCESS".equals(trade_state)) {
                //通过订单号从redis拿数据
                Object redisCdo = redisTemplate.get(mapResult.get("out_trade_no"));
                CDO serviceInfo = CDO.copyToNewCDO(redisCdo);
                //更新服务订单状态至venus_project_life_service_cost
                serviceInfo.set("cost_state", 1);//订单状态：0.待支付1.已下单2.已接单3.待评价4.待退款5.已完成
                venusProjectLifeServiceCostDao.addLifeServiceCostRecord(serviceInfo);
            }else {
                return Return.valueOf(-1,"订单处理异常！");
            }
        }
        catch(Exception e)
        {
            return	Return.valueOf(-1,"---------微信支付回调地址处理异常:{}----------");
        }
        return Return.SUCCESS;
    }


    public String rand(String src) {
        Date currTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String time = formatter.format(currTime);
        String timeMillis = currTime.getTime() + "";
        String item = timeMillis.substring(timeMillis.length() - 4);//时间戳后四位
        String codeItem = RandomStrUtil.getRandInt(3);//随机码四位
        String rand = src + time + item + codeItem;
        return rand;
    }

    /**
     * 通过服务id获取该服务所有上架小区
     * @param cdo
     * @return
     */
    @OpenApi
    public Return getAllNeighbourhoodByServiceId(CDO cdoRequest){
        //分页参数
        Integer pageIndex = cdoRequest.containsKey("pageIndex") ? cdoRequest.getInteger("pageIndex") : 0;
        int recordSize = cdoRequest.containsKey("recordSize") ? cdoRequest.getInteger("recordSize") : 10;
        cdoRequest.set("recordFrom", pageIndex * recordSize);
        cdoRequest.set("recordSize", recordSize);
        List<CDO> neighbourhoodList = venueProjectCommercialTenantServiceDao.selectAllNeighbourhoodByServiceId(cdoRequest);
        CDO result = new CDO();
        result.set("datalist", neighbourhoodList);
        Integer total = venueProjectCommercialTenantServiceDao.selectAllNeighbourhoodByServiceIdCount(cdoRequest);
        result.set("total", total);
        return Return.valueOf(result);
    }

    /**
     * 审核商家服务上架
     */
    @OpenApi
    public Return commercialServiceAuditUpLine(CDO cdoRequest){
        if (StringUtils.isEmpty(cdoRequest.getString("tenant_id"))){
            return Return.valueOf(-1,"商户id不能为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("service_id"))){
            return Return.valueOf(-1,"服务id不能为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("service_state"))){
            return Return.valueOf(-1,"服务状态不能为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("service_audit_id"))){
            return Return.valueOf(-1,"审核人id不能为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("audit_user_name"))){
            return Return.valueOf(-1,"审核人姓名不能为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("service_audit_opinion"))){
            return Return.valueOf(-1,"审核意见不能为空！");
        }
        if (cdoRequest.getString("service_state").equals(0)){
            cdoRequest.set("service_state",0);//服务状态0.正常1.下架
            venueProjectCommercialTenantServiceDao.updateServiceByProjectIdAndServiceId(cdoRequest);
            //审批人id
            cdoRequest.set("audit_user_id",cdoRequest.getString("service_audit_id"));
            cdoRequest.set("audit_type",0);//审核结果0审核成功、1审核失败
            //审核意见
            cdoRequest.set("audit_opinion",cdoRequest.getString("service_audit_opinion"));
            cdoRequest.set("audit_type",1);//审核类型0.商家认证1.商家服务上架
            venusProjectCommercialAuditRecordDao.addVenusProjectCommercialAuditRecord(cdoRequest);
            return Return.valueOf(200,"商家服务上架成功！");
        }else {
            //审批人id
            cdoRequest.set("audit_user_id",cdoRequest.getString("service_audit_id"));
            cdoRequest.set("audit_type",1);//审核结果0审核成功、1审核失败
            //审核意见
            cdoRequest.set("audit_opinion",cdoRequest.getString("service_audit_opinion"));
            cdoRequest.set("audit_type",1);//审核类型0.商家认证1.商家服务上架
            venusProjectCommercialAuditRecordDao.addVenusProjectCommercialAuditRecord(cdoRequest);
            return Return.valueOf(200,"商家服务上架失败！");
        }
    }

    /**
     * 商家服务下架
     * @param cdoRequest
     * @return
     */
    @OpenApi
    public Return commercialServiceAuditDownLine(CDO cdoRequest){
        if (StringUtils.isEmpty(cdoRequest.getString("tenant_id"))){
            return Return.valueOf(-1,"商户id不能为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("service_id"))){
            return Return.valueOf(-1,"服务id不能为空！");
        }
        cdoRequest.set("service_state",1);//服务状态0.正常1.下架
        venueProjectCommercialTenantServiceDao.updateServiceByProjectIdAndServiceId(cdoRequest);
        return Return.valueOf(200,"商家该服务下架成功！");
    }
}
